package com.envy.customizekaptcha.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class VerifyCodeController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping(value = "/vercode.jpg")
    public void getVerifyCode(HttpServletResponse response, HttpSession session){
        response.setContentType("image/jpeg");
        String text = defaultKaptcha.createText();
        session.setAttribute("verify_code",text);
        BufferedImage image = defaultKaptcha.createImage(text);
        try {
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(image,"jpg",out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
